package com.example.bluetoothapplication.bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.coszero.utilslibrary.app.AppCheckUtils;
import com.coszero.utilslibrary.utils.LogX;
import com.coszero.utilslibrary.utils.ToastUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * Desc： 蓝牙搜索广播
 *
 * @author xmqian
 * Email:xmqian93@163.com
 * Date: 2020/10/28 0028 09:36
 */
public class BluetoothReceiver extends BroadcastReceiver {
    public static final String TAG = "BluetoothSearchReceiver";
    /**
     * 配对请求弹窗拦截
     */
    public static final String PAIRING_REQUEST = "android.bluetooth.device.action.PAIRING_REQUEST";
    /**
     * 新设备
     */
    private final Set<String> mNewDevicesSet = new HashSet<String>();
    /**
     * 已配对设备
     */
    private final Set<String> mPairedDevicesSet = new HashSet<String>();
    /**
     * 所有和已配对的设备列表
     */
    private final List<BluetoothDevice> mDeviceList = new ArrayList<>();
    private BluetoothListener listener;

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        switch (action) {
            case BluetoothDevice.ACTION_FOUND:
                //搜索蓝牙广播
                LogX.i(TAG, "搜索蓝牙");
                searchBluetoothResult(device);
                break;
            case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                //搜索蓝牙结束
                LogX.i(TAG, "搜索蓝牙结束");
                ToastUtils.showMsg("搜索蓝牙结束");
                if (mNewDevicesSet.isEmpty()) {
                    LogX.w(TAG, "没有搜索到蓝牙设备");
                }
                mNewDevicesSet.clear();
                mPairedDevicesSet.clear();
                mDeviceList.clear();
                break;
            case PAIRING_REQUEST:
                //蓝牙配对请求
                LogX.i(TAG, "蓝牙配对请求");
                if (device != null) {
                    try {
                        //(三星)4.3版本测试手机还是会弹出用户交互页面(闪一下)，如果不注释掉下面这句页面不会取消但可以配对成功。(中兴，魅族4(Flyme 6))5.1版本手机两中情况下都正常
                        //ClsUtils.setPairingConfirmation(mBluetoothDevice.getClass(), mBluetoothDevice, true);
                        abortBroadcast();//如果没有将广播终止，则会出现一个一闪而过的配对框。
                        //3.调用setPin方法进行配对...
                        boolean ret = ClsUtils.setPin(device.getClass(), device, "0000");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case BluetoothDevice.ACTION_ACL_CONNECTED:
                //蓝牙已连接
                String linkDeviceName = "";
                if (device != null) {
                    linkDeviceName = AppCheckUtils.checkString(device.getName());
                }
                LogX.i(TAG, "蓝牙已连接:" + linkDeviceName);
                ToastUtils.showMsg("配对成功");
                if (listener != null) {
                    listener.connection(true);
                }
                break;
            case BluetoothDevice.ACTION_ACL_DISCONNECTED:
                //蓝牙已断开
                LogX.i(TAG, "蓝牙已断开");
                ToastUtils.showMsg("蓝牙已断开");
                if (listener != null) {
                    listener.connection(false);
                }
                break;
        }
    }

    public void setListener(BluetoothListener listener) {
        this.listener = listener;
    }

    /**
     * 搜索蓝牙返回
     *
     * @param device device
     */
    private void searchBluetoothResult(BluetoothDevice device) {
        if (device != null) {
            String address = device.getAddress();
            String name;
            if ((!mNewDevicesSet.contains(address)) && (!mPairedDevicesSet.contains(address))) {
                mNewDevicesSet.add(address);
                name = device.getName();
                if ((name == null) || name.isEmpty()) {
                    name = "<New Device>";
                }
//                if (name.startsWith(BLUETOOTH_STARTSWITH_NAME))
                mDeviceList.add(device);
                if (null != listener) {
                    listener.bluetoothList(mDeviceList);
                }
                LogX.i(TAG, "搜索蓝牙信息:" + name + "  " + device.getAddress());
            }
        } else {
            Log.e(TAG, "Could not get parcelable extra from device: " + BluetoothDevice.EXTRA_DEVICE);
        }
    }
}
